<template>
  <div class="role-list-container">
    <!-- 搜索和操作区域 -->
    <el-card class="search-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <el-icon><Setting /></el-icon>
            <span>角色管理</span>
          </div>
          <div class="header-operations">
            <el-button type="primary" @click="handleAdd" plain>
              <el-icon><Plus /></el-icon>添加角色
            </el-button>
            <el-button @click="fetchData" plain>
              <el-icon><Refresh /></el-icon>刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="illustration-container">
        <img src="https://img.icons8.com/color/96/000000/conference-call.png" alt="Role Management Illustration" class="illustration-image">
        <div class="illustration-text">
          <h3>角色权限管理</h3>
          <p>管理系统角色和权限分配，确保系统安全和功能访问控制</p>
        </div>
      </div>
      
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.name" placeholder="请输入角色名称" clearable>
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input v-model="searchForm.code" placeholder="请输入角色编码" clearable>
            <template #prefix>
              <el-icon><Document /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>角色列表</span>
          <el-tag type="info">共 {{ tableData.length }} 条记录</el-tag>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        stripe
        highlight-current-row
        :header-cell-style="{background:'#f5f7fa', color:'#606266'}"
        :empty-text="'暂无角色数据'"
      >
        
        <el-table-column prop="name" label="角色名称" width="180">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Avatar /></el-icon>
              <span>{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="code" label="角色编码" width="180">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Document /></el-icon>
              <span>{{ scope.row.code }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><ChatDotRound /></el-icon>
              <span>{{ scope.row.description }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="300">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button 
                size="small" 
                type="primary" 
                @click="handleEdit(scope.row)"
                :disabled="scope.row.code === 'ROLE_ADMIN'"
                text
              >
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button 
                size="small" 
                type="success" 
                @click="handlePermissions(scope.row)"
                text
              >
                <el-icon><Key /></el-icon>权限设置
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleDelete(scope.row)"
                :disabled="scope.row.code === 'ROLE_ADMIN'"
                text
              >
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑角色对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '添加角色' : '编辑角色'" width="500px">
      <el-form
        :model="roleForm"
        :rules="roleRules"
        ref="roleFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="roleForm.code" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog v-model="permissionDialogVisible" title="权限设置" width="700px">
      <div v-loading="permissionLoading">
        <div class="permission-header">
          <h3>{{ currentRole.name }} 权限配置</h3>
        </div>
        
        <div class="permission-tree-container">
          <el-tree
            ref="permissionTree"
            :data="permissionTree"
            show-checkbox
            node-key="id"
            :default-checked-keys="checkedPermissions"
            :props="{
              label: 'name',
              children: 'children'
            }"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePermissions" :loading="savePermissionLoading">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  Plus, 
  Refresh, 
  Setting, 
  Search, 
  Document, 
  Avatar, 
  Edit, 
  Delete, 
  Key,
  ChatDotRound
} from '@element-plus/icons-vue';
import axios from 'axios';

// 数据加载状态
const loading = ref(false);
const submitLoading = ref(false);
const permissionLoading = ref(false);
const savePermissionLoading = ref(false);

// 搜索表单
const searchForm = reactive({
  name: '',
  code: ''
});

// 表格数据
const tableData = ref([
  { id: 1, name: '超级管理员', code: 'ROLE_ADMIN', description: '系统超级管理员，拥有所有权限' },
  { id: 2, name: '小区管理员', code: 'ROLE_MANAGER', description: '小区管理员，负责管理指定小区' },
  { id: 3, name: '业主', code: 'ROLE_OWNER', description: '业主用户，可以查看自己的房产和提交服务请求' },
  { id: 4, name: '普通员工', code: 'ROLE_STAFF', description: '物业普通员工，处理日常事务' }
]);

// 角色表单
const roleForm = reactive({
  id: null,
  name: '',
  code: '',
  description: ''
});

// 表单验证规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^ROLE_[A-Z_]+$/, message: '角色编码格式应为ROLE_XXX', trigger: 'blur' }
  ]
};

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref('add'); // 'add' 或 'edit'
const roleFormRef = ref(null);

// 权限相关
const permissionDialogVisible = ref(false);
const permissionTree = ref([
  {
    id: 1,
    name: '小区管理',
    children: [
      { id: 101, name: '查看小区列表' },
      { id: 102, name: '添加小区' },
      { id: 103, name: '编辑小区' },
      { id: 104, name: '删除小区' }
    ]
  },
  {
    id: 2,
    name: '房产管理',
    children: [
      { id: 201, name: '查看栋数列表' },
      { id: 202, name: '添加栋数' },
      { id: 203, name: '编辑栋数' },
      { id: 204, name: '删除栋数' },
      { id: 205, name: '查看房产列表' },
      { id: 206, name: '添加房产' },
      { id: 207, name: '编辑房产' },
      { id: 208, name: '删除房产' }
    ]
  },
  {
    id: 3,
    name: '人员管理',
    children: [
      { id: 301, name: '查看业主列表' },
      { id: 302, name: '添加业主' },
      { id: 303, name: '编辑业主' },
      { id: 304, name: '删除业主' },
      { id: 305, name: '查看车辆列表' },
      { id: 306, name: '添加车辆' },
      { id: 307, name: '编辑车辆' },
      { id: 308, name: '删除车辆' }
    ]
  },
  {
    id: 4,
    name: '车位管理',
    children: [
      { id: 401, name: '查看车位列表' },
      { id: 402, name: '添加车位' },
      { id: 403, name: '编辑车位' },
      { id: 404, name: '删除车位' },
      { id: 405, name: '查看使用记录' },
      { id: 406, name: '添加使用记录' },
      { id: 407, name: '编辑使用记录' },
      { id: 408, name: '删除使用记录' }
    ]
  },
  {
    id: 5,
    name: '服务管理',
    children: [
      { id: 501, name: '查看活动列表' },
      { id: 502, name: '添加活动' },
      { id: 503, name: '编辑活动' },
      { id: 504, name: '删除活动' },
      { id: 505, name: '查看报修列表' },
      { id: 506, name: '处理报修' },
      { id: 507, name: '查看投诉列表' },
      { id: 508, name: '处理投诉' },
      { id: 509, name: '查看信箱列表' },
      { id: 510, name: '回复信箱' }
    ]
  },
  {
    id: 6,
    name: '系统管理',
    children: [
      { id: 601, name: '查看用户列表' },
      { id: 602, name: '添加用户' },
      { id: 603, name: '编辑用户' },
      { id: 604, name: '删除用户' },
      { id: 605, name: '查看角色列表' },
      { id: 606, name: '添加角色' },
      { id: 607, name: '编辑角色' },
      { id: 608, name: '删除角色' },
      { id: 609, name: '查看权限列表' },
      { id: 610, name: '权限配置' }
    ]
  }
]);

const permissionTree$ = ref(null);
const checkedPermissions = ref([]);
const currentRole = ref({});

// 初始化
onMounted(() => {
  fetchData();
});

// 获取角色列表数据
const fetchData = async () => {
  loading.value = true;
  try {
    const token = localStorage.getItem('token');
    const response = await axios.get('/api/roles', {
      headers: { Authorization: `Bearer ${token}` }
    });
    
    // 处理后端返回的数据
    if (response.data) {
      tableData.value = response.data;
    } else {
      // 如果后端API未实现，使用模拟数据
      tableData.value = [
        { id: 1, name: '超级管理员', code: 'ROLE_ADMIN', description: '系统超级管理员，拥有所有权限' },
        { id: 2, name: '小区管理员', code: 'ROLE_MANAGER', description: '小区管理员，负责管理指定小区' },
        { id: 3, name: '业主', code: 'ROLE_OWNER', description: '业主用户，可以查看自己的房产和提交服务请求' },
        { id: 4, name: '普通员工', code: 'ROLE_STAFF', description: '物业普通员工，处理日常事务' }
      ];
    }
  } catch (error) {
    console.error('获取角色列表失败:', error);
    ElMessage.error('获取角色列表失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    
    // 使用模拟数据作为备选
    tableData.value = [
      { id: 1, name: '超级管理员', code: 'ROLE_ADMIN', description: '系统超级管理员，拥有所有权限' },
      { id: 2, name: '小区管理员', code: 'ROLE_MANAGER', description: '小区管理员，负责管理指定小区' },
      { id: 3, name: '业主', code: 'ROLE_OWNER', description: '业主用户，可以查看自己的房产和提交服务请求' },
      { id: 4, name: '普通员工', code: 'ROLE_STAFF', description: '物业普通员工，处理日常事务' }
    ];
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  loading.value = true;
  // 模拟搜索
  setTimeout(() => {
    const filteredData = tableData.value.filter(item => {
      const nameMatch = !searchForm.name || item.name.includes(searchForm.name);
      const codeMatch = !searchForm.code || item.code.includes(searchForm.code);
      return nameMatch && codeMatch;
    });
    tableData.value = filteredData;
    loading.value = false;
  }, 300);
};

// 重置搜索
const resetSearch = () => {
  searchForm.name = '';
  searchForm.code = '';
  fetchData();
};

// 添加角色
const handleAdd = () => {
  dialogType.value = 'add';
  resetRoleForm();
  dialogVisible.value = true;
};

// 编辑角色
const handleEdit = (row) => {
  dialogType.value = 'edit';
  resetRoleForm();
  
  // 填充表单
  Object.keys(roleForm).forEach(key => {
    if (row[key] !== undefined) {
      roleForm[key] = row[key];
    }
  });
  
  dialogVisible.value = true;
};

// 删除角色
const handleDelete = (row) => {
  if (row.code === 'ROLE_ADMIN') {
    ElMessage.warning('不能删除超级管理员角色');
    return;
  }
  
  ElMessageBox.confirm(
    `确定要删除角色 ${row.name} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const token = localStorage.getItem('token');
      await axios.delete(`/api/roles/${row.id}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      
      // 从表格中移除
      tableData.value = tableData.value.filter(item => item.id !== row.id);
      
      ElMessage.success('删除成功');
    } catch (error) {
      console.error('删除角色失败:', error);
      ElMessage.error('删除角色失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 重置角色表单
const resetRoleForm = () => {
  roleForm.id = null;
  roleForm.name = '';
  roleForm.code = '';
  roleForm.description = '';
  
  if (roleFormRef.value) {
    roleFormRef.value.resetFields();
  }
};

// 提交表单
const submitForm = async () => {
  if (!roleFormRef.value) return;
  
  await roleFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    submitLoading.value = true;
    try {
      const token = localStorage.getItem('token');
      const headers = { Authorization: `Bearer ${token}` };
      
      if (dialogType.value === 'add') {
        // 创建角色
        const response = await axios.post('/api/roles', roleForm, { headers });
        
        // 添加到表格
        tableData.value.push(response.data);
        
        ElMessage.success('角色创建成功');
      } else {
        // 更新角色
        const response = await axios.put(`/api/roles/${roleForm.id}`, roleForm, { headers });
        
        // 更新表格
        const index = tableData.value.findIndex(item => item.id === roleForm.id);
        if (index !== -1) {
          tableData.value[index] = response.data;
        }
        
        ElMessage.success('角色更新成功');
      }
      
      dialogVisible.value = false;
    } catch (error) {
      console.error('保存角色失败:', error);
      ElMessage.error('保存角色失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    } finally {
      submitLoading.value = false;
    }
  });
};

// 权限设置
const handlePermissions = (row) => {
  currentRole.value = row;
  permissionDialogVisible.value = true;
  permissionLoading.value = true;
  
  const token = localStorage.getItem('token');
  
  // 获取角色的权限
  axios.get(`/api/roles/${row.id}/permissions`, {
    headers: { Authorization: `Bearer ${token}` }
  })
  .then(response => {
    // 设置选中的权限
    if (response.data && response.data.permissionIds) {
      checkedPermissions.value = response.data.permissionIds;
    } else {
      // 如果API未实现，使用模拟数据
      if (row.code === 'ROLE_ADMIN') {
        // 超级管理员拥有所有权限
        checkedPermissions.value = getAllPermissionIds();
      } else if (row.code === 'ROLE_MANAGER') {
        // 小区管理员拥有除系统管理外的所有权限
        checkedPermissions.value = [
          101, 102, 103, 104, 
          201, 202, 203, 204, 205, 206, 207, 208,
          301, 302, 303, 304, 305, 306, 307, 308,
          401, 402, 403, 404, 405, 406, 407, 408,
          501, 502, 503, 504, 505, 506, 507, 508, 509, 510
        ];
      } else if (row.code === 'ROLE_OWNER') {
        // 业主只有查看和服务请求权限
        checkedPermissions.value = [505, 506, 507, 508, 509];
      } else if (row.code === 'ROLE_STAFF') {
        // 普通员工有基本操作权限
        checkedPermissions.value = [
          101, 201, 205, 301, 305, 401, 405, 
          501, 505, 506, 507, 508, 509, 510
        ];
      }
    }
  })
  .catch(error => {
    console.error('获取角色权限失败:', error);
    ElMessage.error('获取角色权限失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    
    // 使用模拟数据作为备选
    if (row.code === 'ROLE_ADMIN') {
      // 超级管理员拥有所有权限
      checkedPermissions.value = getAllPermissionIds();
    } else if (row.code === 'ROLE_MANAGER') {
      // 小区管理员拥有除系统管理外的所有权限
      checkedPermissions.value = [
        101, 102, 103, 104, 
        201, 202, 203, 204, 205, 206, 207, 208,
        301, 302, 303, 304, 305, 306, 307, 308,
        401, 402, 403, 404, 405, 406, 407, 408,
        501, 502, 503, 504, 505, 506, 507, 508, 509, 510
      ];
    } else if (row.code === 'ROLE_OWNER') {
      // 业主只有查看和服务请求权限
      checkedPermissions.value = [505, 506, 507, 508, 509];
    } else if (row.code === 'ROLE_STAFF') {
      // 普通员工有基本操作权限
      checkedPermissions.value = [
        101, 201, 205, 301, 305, 401, 405, 
        501, 505, 506, 507, 508, 509, 510
      ];
    }
  })
  .finally(() => {
    permissionLoading.value = false;
  });
};

// 保存权限设置
const savePermissions = async () => {
  savePermissionLoading.value = true;
  
  try {
    // 获取选中的权限ID
    const permissionTreeRef = permissionTree$.value;
    const checkedKeys = permissionTreeRef ? permissionTreeRef.getCheckedKeys() : [];
    const halfCheckedKeys = permissionTreeRef ? permissionTreeRef.getHalfCheckedKeys() : [];
    const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys];
    
    const token = localStorage.getItem('token');
    await axios.post(`/api/roles/${currentRole.value.id}/permissions`, {
      permissionIds: allCheckedKeys
    }, {
      headers: { Authorization: `Bearer ${token}` }
    });
    
    ElMessage.success('权限设置保存成功');
    permissionDialogVisible.value = false;
  } catch (error) {
    console.error('保存权限设置失败:', error);
    ElMessage.error('保存权限设置失败: ' + (error.response?.data?.message || error.message || '未知错误'));
  } finally {
    savePermissionLoading.value = false;
  }
};

// 获取所有权限ID
const getAllPermissionIds = () => {
  const ids = [];
  
  const extractIds = (nodes) => {
    if (!nodes) return;
    
    nodes.forEach(node => {
      ids.push(node.id);
      if (node.children) {
        extractIds(node.children);
      }
    });
  };
  
  extractIds(permissionTree.value);
  return ids;
};
</script>

<style scoped>
.role-list-container {
  padding: 10px;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}

.header-title {
  display: flex;
  align-items: center;
}

.header-title .el-icon {
  font-size: 22px;
  margin-right: 8px;
  color: #409EFF;
}

.header-operations {
  display: flex;
  gap: 10px;
}

.header-operations :deep(.el-button) {
  font-size: 16px;
  height: 42px;
  padding: 8px 16px;
}

.header-operations :deep(.el-icon) {
  font-size: 18px;
  margin-right: 5px;
}

/* 插图容器样式 */
.illustration-container {
  display: flex;
  align-items: center;
  background-color: #f0f9ff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
}

.illustration-image {
  width: 80px;
  height: 80px;
  margin-right: 20px;
}

.illustration-text h3 {
  font-size: 20px;
  color: #409EFF;
  margin: 0 0 8px 0;
}

.illustration-text p {
  font-size: 16px;
  color: #606266;
  margin: 0;
}

.search-form {
  display: flex;
  align-items: center;
}

.search-form :deep(.el-form-item__label) {
  font-size: 16px;
}

.search-form :deep(.el-input__inner) {
  font-size: 16px;
  height: 42px;
}

.search-form :deep(.el-button) {
  font-size: 16px;
  height: 42px;
  padding: 10px 20px;
}

/* 表格卡片样式 */
.table-card {
  margin-bottom: 20px;
}

.table-card :deep(.el-table) {
  font-size: 16px;
}

.table-card :deep(.el-table th) {
  font-size: 16px;
  padding: 12px 0;
}

.table-card :deep(.el-table td) {
  padding: 12px 0;
}

.cell-with-icon {
  display: flex;
  align-items: center;
  font-size: 16px;
}

.cell-with-icon .el-icon {
  margin-right: 5px;
  font-size: 18px;
}

/* 操作按钮样式 */
.operation-buttons {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 8px;
}

/* 权限设置样式 */
.permission-header {
  margin-bottom: 20px;
}

.permission-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
}

.permission-tree-container {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  padding: 10px;
}

/* 对话框样式 */
:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
}

:deep(.el-form-item__label) {
  font-size: 16px;
}

:deep(.el-input__inner) {
  font-size: 16px;
}

:deep(.el-button) {
  font-size: 16px;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .illustration-container {
    flex-direction: column;
    text-align: center;
  }
  
  .illustration-image {
    margin-right: 0;
    margin-bottom: 15px;
  }
}
</style> 